import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { MatSnackBar } from '@angular/material/snack-bar'; // 你可以使用 Angular Material Snackbar 来显示提示信息
import { Router } from '@angular/router';


@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private snackBar: MatSnackBar,
              private router: Router) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 403) {
          // 如果状态码是 403，则弹出提示框
          this.snackBar.open('你没有权限访问此资源,请先登录', '关闭', {
            duration: 3000,
            horizontalPosition: 'center',  // 水平居中
            verticalPosition: 'top',       // 顶部显示
            panelClass: ['custom-snackbar'] // 添加自定义的 CSS 类
          });

          // 跳转到登录页，并携带当前 URL 作为 returnUrl
          const currentUrl = this.router.url;  // 获取当前路由
          this.router.navigate(['./users/login'], { queryParams: { returnUrl: currentUrl } });

        }
        return throwError(error); // 将错误重新抛出
      })
    );
  }
}
